package com.tanhan.mindapp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhan.mindapp.dao.Result;
import com.tanhan.mindapp.dao.SysUser;
import com.tanhan.mindapp.dao.SysUserDTO.SysUserCreateDTO;
import com.tanhan.mindapp.dao.SysUserDTO.SysUserQueryDTO;
import com.tanhan.mindapp.service.SysUserRoleService;
import com.tanhan.mindapp.service.SysUserService;
import com.tanhan.mindapp.dao.SysMenu;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/system/sysUser")
@Tag(name = "系统用户管理", description = "管理系统中用户信息的增删改查操作")
@Slf4j
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @GetMapping("/findAll")
    @Operation(summary = "查询所有用户", description = "获取系统中所有用户的列表信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<List<SysUser>> list() {
        List<SysUser> list = sysUserService.list();
        return Result.success(list);
    }

    @GetMapping("/findById/{id}")
    @Operation(summary = "根据ID查询用户", description = "根据用户唯一标识符查询单个用户的详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<SysUser> getById(@PathVariable String id) {
        SysUser user = sysUserService.getUserWithRoles(id);
        return Result.success(user);
    }

    @PostMapping("/add")
    @Operation(summary = "添加用户", description = "添加新用户到系统中")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    public Result<?> addUser(@RequestBody SysUserCreateDTO sysUser) {
        boolean result = sysUserService.addUser(sysUser);
        if (result) {
            return Result.success("用户添加成功");
        } else {
            return Result.error(500, "用户添加失败");
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户", description = "根据用户ID更新用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    public Result<Void> update(@RequestBody SysUser sysUser) {
        boolean isSuccess = sysUserService.updateById(sysUser);
        if (isSuccess) {
            return Result.success();
        } else {
            return Result.error(9999, "更新用户失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户", description = "根据用户ID删除指定用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    public Result<Void> delete(@PathVariable Long id) {
        sysUserService.removeById(id);
        return Result.success();
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询用户", description = "根据条件分页查询用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<IPage<SysUser>> page(@RequestBody SysUserQueryDTO sysUserQueryDTO) {
        IPage<SysUser> pageResult = sysUserService.selectUserPage(sysUserQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/assignRoles/{userId}")
    @Operation(summary = "分配角色", description = "为指定用户分配角色")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    public Result<Boolean> assignRoles(@PathVariable String userId, @RequestBody List<String> roleIds) {
        try {
            boolean result = sysUserRoleService.assignRolesToUser(userId, roleIds);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error(500, "角色分配失败");
            }
        } catch (Exception e) {
            log.error("分配角色失败，用户ID: {}, 角色IDs: {}", userId, roleIds, e);
            return Result.error(500, "角色分配异常: " + e.getMessage());
        }
    }

    @GetMapping("/getUserRoles/{userId}")
    @Operation(summary = "获取用户角色", description = "获取指定用户已分配的角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public Result<List<String>> getUserRoles(@PathVariable String userId) {
        try {
            List<String> roleIds = sysUserRoleService.getRoleIdsByUserId(userId);
            return Result.success(roleIds);
        } catch (Exception e) {
            log.error("获取用户角色失败，用户ID: {}", userId, e);
            return Result.error(500, "获取用户角色异常: " + e.getMessage());
        }
    }

    @GetMapping("/getUserMenus")
    @Operation(summary = "获取用户菜单", description = "根据用户token获取用户有权访问的菜单列表")
    public Result<List<SysMenu>> getUserMenus(@RequestHeader("Authorization") String token) {
        try {
            // 移除Bearer前缀（如果存在）
            String jwtToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            List<SysMenu> menus = sysUserService.getUserMenusByToken(jwtToken);
            return Result.success(menus);
        } catch (Exception e) {
            log.error("获取用户菜单失败", e);
            return Result.error(500, "获取用户菜单失败: " + e.getMessage());
        }
    }

}
